package com.zhongkun.datahome.framework.security.provider;

import com.zhongkun.datahome.framework.security.context.WechatAuthenticationToken;
import com.zhongkun.datahome.framework.web.service.WeixinUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

@Component
public class WechatAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private WeixinUserDetailsService weixinUserDetailsService;

    @Override
    public Authentication authenticate(Authentication auth) {
        String phoneNumber = ((WechatAuthenticationToken) auth).getPhoneNumber();
        UserDetails user = weixinUserDetailsService.loadByMobile(phoneNumber);
        return new WechatAuthenticationToken(user, phoneNumber);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return WechatAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.weixinUserDetailsService = (WeixinUserDetailsService) userDetailsService;
    }

}